# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 12:57:27 2018

@author: nxleisp
"""

# curl -u admin@zaadmin01:zaadmin01 -i http://10.70.49.31/tsdbrest/api/token

# curl -u admin@zaadmin01:zaadmin01 -i http://10.70.49.31/tsdbrest/api/instance


# http://10.70.49.31/tsdbrest/api/instance/range/1234/7?limit=10&start_time=1442559920000&end_time=1442559970000&cursor_mask=*&token=bea1e09da4a34d07bd638f052fce73b5

# from properties import tsdb_host, tsdb_port, tsdb_username, tsdb_password, tsdb_tablename
import pandas
import requests
from requests.auth import HTTPBasicAuth
import json, time


class xtsdb():
    _host = ''
    _port = ''
    _user = ''
    _pswd = ''
    _url_token = ''
    _url_instance = ''
    _url_record = ''
    _url_tag = ''
    _token = ''

    def __init__(self, host='10.70.248.213', port=80, user='admin@BGTATOADMN01', pswd='FdS8_wq12A'):
        self._host = host
        self._port = port
        self._user = user
        self._pswd = pswd
        self._url_base = 'http://%s:%s' % (host, port)
        self._url_token = self._url_base + '/tsdbrest/api/token'
        self._url_instance = self._url_base + '/tsdbrest/api/instance'
        self._url_record = self._url_base + '/tsdbrest/api/record'
        self._url_tag = self._url_base + '/tsdbrest/api/tag'
        # self._url_tagquery = self._url_base + '/tsdbrest/api/tag/querybytagname'
        self.getToken()

    def getToken(self):
        r = requests.get(self._url_token, auth=(self._user, self._pswd))
        self._token = r.json()['token']
        return r.json()

    def getInstance(self, instance_name, property_names=None):
        headers = {'Content-Type': 'application/json'}
        if (property_names == None):
            r = requests.post(self._url_instance, data=json.dumps([{"instance_name": instance_name}]), headers=headers,
                              auth=(self._user, self._pswd))
        else:
            r = requests.post(self._url_instance,
                              data=json.dumps([{"instance_name": instance_name, "property_names": property_names}]),
                              headers=headers, auth=(self._user, self._pswd))
        return r.json()

    def putRecord(self, instance_id, property_values=None):
        headers = {'Content-Type': 'application/json'}
        r = requests.post(self._url_record,
                          data=json.dumps([{"instance_id": instance_id, "property_values": property_values}]),
                          headers=headers, auth=(self._user, self._pswd))
        return r.json()

    def getSnapshot(self, instance_id, property_ids=None):
        headers = {'Content-Type': 'application/json'}
        r = requests.post(self._url_record + '/snapshot',
                          data=json.dumps([{"instance_id": instance_id, "property_ids": property_ids}]),
                          headers=headers, auth=(self._user, self._pswd))
        return r.json()

    def getHistoryByID(self, instance_id, property_id, limit=10, start_time=None, end_time=None, cursor_mask='*'):
        if (end_time == None):
            end_time = str(time.time()).replace('.', '')[:-4]
        if (start_time == None):
            start_time = str(int(end_time) - 300000)
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record + '/range/%s/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (
            instance_id, property_id, limit, start_time, end_time, cursor_mask)
        # print(request_url)
        r = requests.get(request_url, headers=headers, auth=(self._user, self._pswd))
        # print(r.content)
        return r.json()

    def getHistoryByTagID(self, tag_id, limit=10, start_time=None, end_time=None, cursor_mask='*'):
        if (end_time == None):
            end_time = str(time.time()).replace('.', '')[:-4]
        if (start_time == None):
            start_time = str(int(end_time) - 300000)
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record + '/tag/range/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (
            tag_id, limit, start_time, end_time, cursor_mask)
        # print(request_url)
        r = requests.get(request_url, headers=headers, auth=(self._user, self._pswd))
        # print(r.content)
        return r.json()

    def timeconvert(self, stime):
        time_stamp = time.strptime("%Y%m%d%H%M%S", stime)

    def get_time_stamp(self, ct):
        local_time = time.localtime(ct)
        data_head = time.strftime("%Y%m%d_%H%M%S", local_time)
        data_secs = (ct - int(ct)) * 1000
        time_stamp = "%s.%03d" % (data_head, data_secs)
        return time_stamp

    def getHistoryByName(self, instance_name, property_names, limit=10, start_time=None, end_time=None,
                         upper_inclusive='true'):
        if (end_time == None):
            end_time = self.get_time_stamp(time.time())
        if (start_time == None):
            start_time = self.get_time_stamp(time.time() - 300)
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record + '/range/%s?limit=%s&start_time=%s&end_time=%s&upper_inclusive=%s' % (
            instance_name, limit, start_time, end_time, upper_inclusive)
        # print(request_url)
        r = requests.post(request_url, data=json.dumps(property_names), headers=headers, auth=(self._user, self._pswd))
        return r.json()

    def getTagIdByName(self, tagnames, collector_name=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/query?collector_name=' + collector_name
        # print(request_url)
        r = requests.post(request_url, data=json.dumps(tagnames), headers=headers, auth=(self._user, self._pswd))
        # print('======运行状态码：' + str(r.status_code))
        mess = r.json()
        rst = None
        # if(collector_name == None):
        #     rst = r.json()['records']
        # else:
        #     for x in r.json()['records']:
        #         if(x['collector_name'] == collector_name):
        #             rst = [x]
        # print(rst)
        if mess['errcode'] == 0:
            rst = [tag['id'] for tag in mess['tags']]
        return rst

    def getTagIdByNames(self, tagnames, collector_name=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/querybytagname'
        # print(request_url)
        r = requests.post(request_url, data=json.dumps(tagnames), headers=headers, auth=(self._user, self._pswd))
        return r.json()['records']

    def getTagNameByCollector(self, collector_names=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/querybycollectorname?limit=1000&offset=0'
        # print(request_url)
        r = requests.post(request_url, data=json.dumps(collector_names), headers=headers, auth=(self._user, self._pswd))
        return r.json()

    def getHistoryByTagNames(self, collector_name, tag_names, limit=1000, start_time=None, end_time=None,
                             cursor_mask='*', minutes=5):
        """
        通过TagName获取一段时间值
        :param collector_name:
        :param tag_names:
        :param limit:
        :param start_time:
        :param end_time:
        :param cursor_mask:
        :param minutes:
        :return:
        {
            "tag_name":{
                'errcode': 0,
                'records': [{
                    'quality': 100,
                    'timestamp': 1667146851999,
                    'value': '0.75',
                    'type': 'FLOAT64',
                    'id': 283149
                }, {
                    'quality': 100,
                    'timestamp': 1667146873033,
                    'value': '0.75',
                    'type': 'FLOAT64',
                    'id': 283149
                }, {
                    'quality': 100,
                    'timestamp': 1667146894985,
                    'value': '0.7699999809265137',
                    'type': 'FLOAT64',
                    'id': 283149
                }, {
                    'quality': 100,
                    'timestamp': 1667146916008,
                    'value': '0.7699999809265137',
                    'type': 'FLOAT64',
                    'id': 283149
                }, {
                    'quality': 100,
                    'timestamp': 1667146959094,
                    'value': '0.75',
                    'type': 'FLOAT64',
                    'id': 283149
                }, {
                    'quality': 100,
                    'timestamp': 1667146981164,
                    'value': '0.800000011920929',
                    'type': 'FLOAT64',
                    'id': 283149
                }],
                'next_cursor_mask': '1667146981165'
            }
        }
        """
        tag_ids = []
        rst = {}
        if (end_time == None):
            end_time = str(time.time()).replace('.', '')[:-4]
        if (start_time == None):
            start_time = str(int(end_time) - minutes * 60 * 1000)
        headers = {'Content-Type': 'application/json'}
        for tag_name in tag_names:
            tag_idrst = self.getTagIdByName([tag_name], collector_name)
            if (tag_idrst != None):
                tag_id = tag_idrst[0]
                tag_ids.append(tag_id)
                request_url = self._url_record + '/tag/range/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (
                    tag_id, limit, start_time, end_time, cursor_mask)
                # print(request_url)
                r = requests.get(request_url, headers=headers, auth=(self._user, self._pswd))
                # print('getHistoryByTagNames 状态码：' + str(r.status_code))
                # print('getHistoryByTagNames value：' + str(r.json()))
                rst[tag_name] = r.json()
            # print(r.content)
        return rst

    def getSnapshotByTagIDs(self, tag_ids):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record + '/tag/snapshot'
        # print(request_url)
        r = requests.post(request_url, data=json.dumps(tag_ids), headers=headers, auth=(self._user, self._pswd))
        return r.json()


# tsdb = xtsdb(host='10.70.248.213', port=80, user='admin@BGTMTOADMN01', pswd='ZAQop_yg')
# tsdb = xtsdb(host='10.70.248.213', port=80, user='admin@BGTATOADMN01', pswd='FdS8_wq12A')
tsdb = xtsdb(host='10.70.248.213', port=80, user='admin@BGTATOADMN02', pswd='gDsy_Q1wee')

if __name__ == '__main__':
    # xdb = xtsdb(host='10.70.248.213', user='admin@BGTATOADMN01', pswd='FdS8_wq12A')
    # xdb = xtsdb(host='10.70.248.213', user='admin@BGTMTOADMN01', pswd='ZAQop_yg')
    xdb = xtsdb(host='10.70.248.213', user='admin@BGTATOADMN02', pswd='gDsy_Q1wee')
    r = xdb.getHistoryByTagNames('BGTATOAD01', ["BS_310315E26_R2_MD_Bot_NDSBearTemp_Act"],
                                 start_time=1672502400000, end_time=1684348302932, minutes=5)
    # r = xdb.getHistoryByTagNames('BGTATOEMFN', ["BS_323539E01_MFSIDERBG_HVIB_IMPC_RMS"],
    #                              start_time=1672502400000, end_time=1680278400000, minutes=5)

    # r = xdb.getHistoryByTagNames('BGTATOAD01', ["BS_310205E11_HF4_LEFT_PUSHER_MOTOR_HBRAKE_OPERATE_SIGNAL"],
    #                              start_time=1680278400000, end_time=1682870400000, minutes=5)

    # r = xdb.getHistoryByTagNames('BGTATOEMFN', ["BS_650784E01_MOTOR_BODY_WINDING_TEMP1"],
    #                              start_time=1672713780000, end_time=1672800180000, minutes=5)
    # r = xdb.getHistoryByTagNames('BGTMTOAE01', ["MS_451205E01_2_DECOILER_MOTOR_BEARSIDE_BEARING_VERT_VIB_SPEED_EFFVAL"],
    #                              start_time=1678582800000, end_time=1678671000000, minutes=5)
    print(r)
# def test():
#    #xdb = xtsdb()
#    xdb = xtsdb(host='10.70.50.121')
#    tk = xdb.getToken()
#    print(tk)
#    print('test for getInstance')
#    r = xdb.getInstance('test')
#    print(r)
#    print('test for getSnapshot')
#    r = xdb.getSnapshot('11423',[])
#    print(r)
#    r = xdb.getHistoryByTagNames('tongweisu1580',["Status.XRay1HighVoltage","Status.XRay1TubeCurrent"],minutes=1000)
##    print(r["Status.XRay1HighVoltage"]["records"])
#    import pandas as pd
#    
#    data = pd.DataFrame(r["Status.XRay1HighVoltage"]["records"])
#    print(data)
##    print(r)
#    print(r.items())
#    print(r.keys())
#    xdb.timeconvert("1543506589954")
#    print('test for getHistoryByID')
#    r = xdb.getHistoryByID('11423',6)
#    print(r)
#    print('test for getTagIdByName')
#    r = xdb.getTagIdByName(["Setup.CrownUpper"],'tongweisu1580')
#    print(r)
#    print('test for getHistoryByTagID')
#    r = xdb.getHistoryByTagID(r[0]['tag_id'])
#    print(r)
#    print('test for getHistoryByTagName')
#    r = xdb.getHistoryByTagNames('tongweisu1580',["Setup.CrownUpper","Setup.CrownLower"])
#    print(r)
#    r = xdb.getHistoryByTagNames('tongweisu1580',["ScanData.CoilID"])
#    print(r)
#    print('test for getTagNameByCollector')
#    r = xdb.getTagNameByCollector(['tongweisu1580'])
#    print(r)
# print('test for getHistoryByName')
# r = xdb.getHistoryByName('test',["FLOAT32"])
# r = xdb.getTags(collector_name='ihd',tag_name='',limit=100,offset=0)


# test()
